import {messages, queryCurrencyPrecision} from "share/common";

import React from 'react'
import { connect } from 'react-redux'
import { Form, Button, InputNumber, Spin, message } from 'antd'
import Apportion from 'containers/confirm-consumption/apportion-frame'
const FormItem = Form.Item;
import confirmSumptionService from './confirm-consumption.service'
import errorMessage from "share/errorMessage";

class EditConsumptionDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      apportionDTOS: [],
    };
  }

  componentDidMount() {
    this.setState({ loading: true }, () => this.getDetail(this.props.recordId))
  }

  getDetail = recordId => {
    let params = {
      channel:'hly-admin',
      recordId
    };
    confirmSumptionService.getApportionDetail(params).then(res => {
      this.setState({
        loading: false,
        apportionDTOS: res.data.apportionDTOS
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ loading: false });
    })
  };

  componentWillReceiveProps(nextProps) {
    if(nextProps.recordId && nextProps.recordId !== this.props.recordId) {
      this.getDetail(nextProps.recordId)
    }
  }

  onCancel = () => this.props.close();

  handleSave = () => {
    const { vendorType, recordId, loginUser: { tenantId } } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let validationSuccess = true;
        if(values.apportionDTOS) {
          let proportion = 0;
          let userId = true;
          let apportionAmount = true;
          values.apportionDTOS.map(apportion => {
            let validationItem = false;
            apportion.costCenterItems && apportion.costCenterItems.map(i => {
              validationItem = validationItem || !!i.costCenterItemOID
            });
            proportion = proportion + apportion.proportion;
            userId = userId && !!apportion.userId;
            apportionAmount = apportionAmount && !!apportion.apportionAmount;
            validationSuccess = validationSuccess && validationItem;
          });
          if(!validationSuccess) {
            message.error(messages('expense-16.key463')/*分摊成本中⼼为空，⽆法保存*/);
            return ;
          }
          if(proportion !== 1) {
            message.error(messages('expense-1.key231')/*分摊比率和需等于100%*/);
            return ;
          }
          if(!apportionAmount) {
            message.error(messages('expense-16.key465')/*分摊金额不能为0*/);
            return ;
          }
        }
        values.apportionDTOS = values.apportionDTOS.map((i, index) => {
          i.lineNum = index + '';
          i.recordId = recordId;
          i.tenantId = tenantId;
          return i;
        });
        let params = {
          channel: 'hly-admin',
          vendorType,
          tenantId,
          recordId,
          ...values
        };
        this.setState({ loading: true });
        confirmSumptionService.saveApportionDetail(params).then(res => {
          this.setState({ loading: false });
          if(res.data.responseCode === '200') {
            message.success(messages('expense-16.key436')/*保存成功*/);
            this.props.close(true);
          } else {
            message.error(res.data.responseMessage || messages('common.save.filed')/*保存失败*/);
          }
        }).catch(e => {
          errorMessage(e.response);
          this.setState({ loading: false });
        })
      }
    });
  };

  render(){
    const { loading, apportionDTOS } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { employeeBearAmount, currencyCode, totalAmount } = this.props;
    return (
      <div className="new-form edit-consumption-detail">
        <Spin spinning={loading}>
          <Form>
            {totalAmount >= 0 &&
              <FormItem label={messages('expense-16.key414')/*个人承担金额*/}>
                {getFieldDecorator('employeeBearAmount',{
                  initialValue: Number(employeeBearAmount || 0),
                  rules: [{
                    type: 'number',
                    max: Number(totalAmount || 0),
                    message: messages('expense-16.key437',{arg1: currencyCode,arg2: this.filterMoney(totalAmount,queryCurrencyPrecision(currencyCode),true)})/*总金额：{arg1} {arg2}，不可大于总金额*/,
                  }]
                })(
                  <InputNumber
                    min={0}
                    precision={queryCurrencyPrecision(currencyCode)}
                  />
                )}
              </FormItem>
            }
            <FormItem  label={messages('expense-16.key434')/*分摊*/}>
              {getFieldDecorator('apportionDTOS',{
                initialValue: apportionDTOS || [],
              })(
                <Apportion amount={Number(totalAmount || 0)} currencyCode={currencyCode} />
              )}
            </FormItem>
            <div className="slide-footer" style={{position: 'fixed'}}>
              <Button type="primary" onClick={this.handleSave}>{messages('common.ok')/*确定*/}</Button>
              <Button onClick={this.onCancel}>{messages('common.back')/*返回*/}</Button>
            </div>
          </Form>
        </Spin>
      </div>
    )

  }

}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser
  }
}

const WrappedEditConsumptionDetail = Form.create()(EditConsumptionDetail);

export default connect(mapStateToProps)(WrappedEditConsumptionDetail)
